#!/usr/bin/env python3
import os
import subprocess
import sys
from lxml import etree

# 工作空间路径，第一个参数
workspace_path = ''
# 分支名，第二个参数，默认：master
project_branch = ''
# 应用版本
project_version = '1.0'
# 临时目录
tmp_path = '/home/devops/.jenkinstmp'
# 本地镜像名称
image_name = ''

# 应用名称
app_name = 'shop-boot'


def init_env():
    """
    初始化环境
        1. 获取工作空间路径
        2. 解析项目版本, 解析pom.xml文件获得，忽略 -SNAPSHOT
    :return:
    """
    print('')
    print('初始化 docker 打包环境')
    global workspace_path
    global project_branch
    global project_version
    global image_name
    global tmp_path
    workspace_path = sys.argv[1]
    project_branch = sys.argv[2]
    print('应用名称:' + app_name)

    tree = etree.parse(workspace_path + '/pom.xml')
    root = tree.getroot()
    for el in root:
        if '{http://maven.apache.org/POM/4.0.0}version' == el.tag:
            project_version = el.text
            project_version = project_version.replace('-SNAPSHOT', '')
    print('应用版本:' + project_version)
    print('项目分支:' + project_branch)
    print('工作空间路径:' + workspace_path)
    image_name = app_name + '-' + project_branch + ':' + project_version
    print('本地镜像名称:' + image_name)
    tmp_path = '/home/devops/.jenkinstmp/' + workspace_path.split('/')[-1]
    if not os.path.isdir(tmp_path):
        os.mkdir(tmp_path)
    print('本地镜像打包临时目录:' + tmp_path)


def has_image():
    """
    判断本地是否已经存在项目对应的分支和版本的镜像
    :return: True | False
    """
    print('')
    print('搜索本地镜像')
    (status, output) = run_shell(
        'docker images -q --filter=reference=' + app_name + ':' + project_version)

    if 0 == status:
        if 0 == len(output):
            return False
        else:
            return True


def del_image():
    """
    删除本地镜像
    :return: 无
    """
    print('')
    print('删除本地镜像:' + image_name)
    sh = 'docker rmi ' + image_name
    run_shell(sh)


def create_image():
    """
    根据项目分支与版本创建镜像
    :return:
    """
    print('')
    print('构建本地镜像' + image_name)
    global tmp_path
    run_shell('rm -rf ' + tmp_path)
    run_shell('mkdir ' + tmp_path)
    run_shell('cp ' + workspace_path + '/Dockerfile ' + tmp_path + '/')
    run_shell('cp ' + workspace_path + '/target/' + app_name + '.jar ' + tmp_path + '/')
    run_shell(
        'cd ' + tmp_path + ' && docker build -t ' + image_name + ' .')


def tar_image():
    """
    打包本地镜像
    :return:
    """
    print('')
    print('打包本地镜像:' + image_name)
    image_tar_path = tmp_path + '/' + app_name + '-' + project_branch + ':' + project_version + '.tar'
    run_shell(
        'docker save -o ' + image_tar_path + ' ' + image_name)
    print('本地镜像打包文件:' + image_tar_path)
    run_shell('ls -lFh --time-style="+%Y-%m-%d %H:%I:%S" ' + image_tar_path)


def run_shell(sh):
    print('====================================================')
    print('shell:' + sh)
    (status, output) = subprocess.getstatusoutput(sh)
    print('shell status:', status)
    print('shell output:')
    print(output)
    print('====================================================')
    print('')
    return status, output


if __name__ == '__main__':
    init_env()
    if has_image():
        print('删除原镜像')
        del_image()
    create_image()
    tar_image()